﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using intera = System.Windows.Interactivity;
using System.Windows.Controls.Primitives;
using System.Reflection;
using System.Windows.Markup;
using MoneyBook.ComponentModel;

namespace MoneyBook.Interactivity {

    [intera.DefaultTrigger(typeof(UIElement), typeof(System.Windows.Interactivity.EventTrigger), "MouseLeftButtonDown")]
    [intera.DefaultTrigger(typeof(ButtonBase), typeof(System.Windows.Interactivity.EventTrigger), "Click")]
    [intera.DefaultTrigger(typeof(Selector), typeof(System.Windows.Interactivity.EventTrigger), "SelectionChanged")]
    [ContentProperty("Parameter")]
    public class SetPropertyAction : intera.TargetedTriggerAction<object>, INotifyActionCompleted {

        public event EventHandler<ActionCompletedEventArgs> ActionCompleted;

        public string PropertyName { get; set; }

        public ParameterBase Parameter {
            get { return (ParameterBase)GetValue(ParameterProperty); }
            set { SetValue(ParameterProperty, value); }
        }

        public static readonly DependencyProperty ParameterProperty =
            DependencyProperty.Register("Parameter", typeof(ParameterBase), typeof(SetPropertyAction), new PropertyMetadata(OnParameterChanged));

        private static void OnParameterChanged(object sender, DependencyPropertyChangedEventArgs e) {

        }

        protected override void Invoke(object parameter) {
            if (this.Target == null || string.IsNullOrWhiteSpace(PropertyName)) {
                return;
            }
            PropertyInfo prop = this.Target.GetType().GetProperty(this.PropertyName, BindingFlags.Public | BindingFlags.Instance);
            if (prop == null) {
                //TODO Message
                throw new InvalidOperationException();
            }
            if (!prop.CanWrite) {
                //TODO Message
                throw new InvalidOperationException();
            }
            if (this.Parameter == null) {
                //TODO Message
                throw new InvalidOperationException();
            }
            object value = TypeConverterHelper.ConvertToType(this.Parameter.GetParameterValue(parameter), prop.PropertyType);
            prop.SetValue(this.Target, value, null);
            if (this.ActionCompleted != null) {
                this.ActionCompleted(this, new ActionCompletedEventArgs(null));
            }
        }
    }
}
